package com.zsh.wanandroid.base;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.kingja.loadsir.callback.Callback;
import com.kingja.loadsir.core.LoadService;
import com.kingja.loadsir.core.LoadSir;

/**
 * @author zsh
 * @date 2020/3/12.
 * 功能：Fragment基类
 */

public abstract class BaseFragment extends Fragment {

    protected static final String BUNDLE_KEY_TITLE = "key_title";

    /**
     * 下拉刷新状态
     */
    public boolean isRefresh = false;
    /**
     * loadingView
     */
    protected LoadService mBaseLoadService;
    /**
     * 是否初始化布局
     */
    protected boolean isViewInitiated;
    /**
     * 当前界面是否可见
     */
    protected boolean isVisibleToUser;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle
            savedInstanceState) {
        View rootView = inflater.inflate(onCreateFragmentView(), container, false);
        mBaseLoadService = LoadSir.getDefault().register(rootView, new Callback.OnReloadListener() {
            @Override
            public void onReload(View v) {
                onNetReload(v);
            }
        });
        return mBaseLoadService.getLoadLayout();
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView(view);
        loadNet();
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
    }

//    @Override
//    public void setUserVisibleHint(boolean isVisibleToUser) {
//        super.setUserVisibleHint(isVisibleToUser);
//        // 是否对用户可见
//        this.isVisibleToUser = isVisibleToUser;
//        if (isVisibleToUser) {
//            //isCanLoadData();
//        }
//    }

    /*
     * 执行数据加载： 条件是view初始化完成并且对用户可见
     */
//    private void isCanLoadData() {
//        if (isViewInitiated && isVisibleToUser) {
//            loadNet();
//            // 加载过数据后，将isViewInitiated和isVisibleToUser设置成false，防止重复加载数据
//            isViewInitiated = false;
//            isVisibleToUser = false;
//        }
//    }

    protected abstract int onCreateFragmentView();

    protected abstract void initView(View view);

    protected abstract void loadNet();

    protected abstract void onNetReload(View v);

}
